// utils/permission.ts
import {callApi} from '@/utils/request';
import {RolePermissionVo, UserPermissionVo} from '@/types/permission';
import {getPermissionsByUser} from "@/services/permission";

export class PermissionUtils {
    private static cache: RolePermissionVo | null = null;
    private static cacheTimestamp: number | null = null;
    private static CACHE_DURATION = 30 * 60 * 1000; // 30分钟缓存

    // 检查缓存是否有效
    private static isCacheValid(): boolean {
        if (!this.cacheTimestamp) return false;
        return Date.now() - this.cacheTimestamp < this.CACHE_DURATION;
    }

    // 获取用户权限（带缓存）
    static async getUserPermissions(): Promise<RolePermissionVo> {
        // 如果缓存有效，直接返回缓存数据
        if (this.cache && this.isCacheValid()) {
            return this.cache;
        }

        try {
            const data = await callApi<RolePermissionVo>(
                () => getPermissionsByUser(),
                {successMsg: '', errorMsg: '权限获取失败'}
            );

            // 检查 data 是否为 null
            if (!data) {
                throw new Error('权限数据获取失败');
            }

            // 保存到缓存和本地存储
            this.cache = data;
            this.cacheTimestamp = Date.now();
            this.savePermissions(data.userPermission);

            return data;
        } catch (error) {
            console.error('获取权限失败:', error);
            throw error;
        }
    }

    // 强制刷新缓存
    static async refreshPermissions(): Promise<RolePermissionVo> {
        this.cache = null;
        this.cacheTimestamp = null;
        return this.getUserPermissions();
    }

    // 清除缓存
    static clearCache(): void {
        this.cache = null;
        this.cacheTimestamp = null;
    }

    // 检查是否有菜单权限
    static hasMenuPermission(code: string): boolean {
        const permissions = this.getPermissions();
        return permissions.menuPermissions.includes(code);
    }

    // 检查是否有按钮权限
    static hasButtonPermission(code: string): boolean {
        const permissions = this.getPermissions();
        return permissions.buttonPermissions.includes(code);
    }

    // 获取权限列表
    static getPermissions(): UserPermissionVo {
        const permissions = localStorage.getItem('userPermissions');
        if (permissions) {
            return JSON.parse(permissions);
        }
        return {menuPermissions: [], buttonPermissions: []};
    }

    // 保存权限到本地存储
    static savePermissions(permissions: UserPermissionVo): void {
        localStorage.setItem('userPermissions', JSON.stringify(permissions));
    }

    // 检查路径是否有权限
    static hasPathPermission(path: string): boolean {
        const permissions = this.getPermissions();
        const pathCode = this.convertPathToCode(path);
        return permissions.menuPermissions.includes(pathCode);
    }

    // 路径转权限码
    private static convertPathToCode(path: string): string {
        return path.replace(/\//g, '_').replace(/:\w+/g, 'detail').replace(/^_/, '');
    }
}